<template>
  <el-select
    :style="{ width: width }"
    v-model="comValue"
    :multiple="multiple"
    collapse-tags
    collapse-tags-tooltip
    placeholder="请选择"
    :disabled="disabled"
    :clearable="clearable"
    :filterable="filterable"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>
<script setup>
import { get_select_options } from '@/api/system'
import { useUserStore } from '@/pinia/modules/user'
const changeTitle = inject('changeTitle', () => {})
const emit = defineEmits(['update:modelValue', 'change'])
const orgInfo = useUserStore().orgInfo
const props = defineProps({
  width: {
    type: String,
    default: '200px'
  },
  filterable: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: String,
    default: useUserStore().orgInfo.level == 5 ? useUserStore().orgInfo.id : ''
  },
  type: {
    type: [String, Number],
    default: ''
  },
  disabled: {
    type: Boolean,
    default: useUserStore().orgInfo.level == 5 ? true : false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: false
  },
  url: {
    type: String,
    default: ''
  },
  searchParams: {
    type: Object,
    default: {}
  },
  watchValue: {
    type: [String, Number],
    default: ''
  },
  optionsFormat: {
    type: Object,
    default: () => {
      return {
        label: 'label',
        value: 'value'
      }
    }
  }
})
const options = ref([])
const comValue = computed({
  get() {
    if (props.multiple) {
      return props.modelValue ? props.modelValue.split(',') : []
    }
    return props.modelValue
  },
  set(val) {
    if (props.multiple) {
      emit('update:modelValue', val.join())
    } else {
      emit('update:modelValue', val)
      let target = options.value.filter(item => item.value == val)[0]
      emit('change', target)
      changeTitle(target)
    }
  }
})

watch(
  () => props.watchValue,
  async val => {
    if (val) {
      await getOptions()
      emit('update:modelValue', '')
    }
  }
)
const getOptions = async () => {
  const res = await get_select_options(props.url, props.searchParams)
  if (res.data && res.data.length > 0) {
    let arr = res.data
    for (let i = 0; i < arr.length; i++) {
      arr[i].label = arr[i][props.optionsFormat.label]
      arr[i].value = arr[i][props.optionsFormat.value]
    }
    options.value = arr
  } else {
    options.value = []
  }
}
onMounted(async () => {
  await getOptions()
  if (useUserStore().orgInfo.level == 5) {
    emit('update:modelValue', useUserStore().orgInfo.id)
    let target = options.value.filter(
      item => item.value == useUserStore().orgInfo.id
    )[0]
    emit('change', target)
  }

})
</script>
<style lang="scss" scoped>
:deep(.el-select__placeholder.is-transparent) {
  font-size: 12px !important;
}
</style>
